package com.education.ai.dao.impl;

import com.education.ai.dao.AdminDao;
import com.education.ai.entity.Admin;
import com.education.ai.util.JdbcUtil;
import com.education.ai.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 管理员数据访问实现类
 */
@Repository
public class AdminDaoImpl implements AdminDao {

    private static final Logger logger = LoggerFactory.getLogger(AdminDaoImpl.class);
    
    @Autowired
    private JdbcUtil jdbcUtil;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    /**
     * 查询所有管理员
     */
    @Override
    public List<Admin> findAll() {
        String sql = "SELECT * FROM admins";
        return mapResultsToAdmins(jdbcUtil.executeQuery(sql));
    }
    
    /**
     * 根据ID查询管理员
     */
    @Override
    public Optional<Admin> findById(Long id) {
        String sql = "SELECT * FROM admins WHERE id = ?";
        List<Map<String, Object>> results = jdbcUtil.executeQuery(sql, id);
        return results.isEmpty() ? Optional.empty() : Optional.of(mapRowToAdmin(results.get(0)));
    }
    
    /**
     * 根据管理员ID查询管理员
     */
    @Override
    public Optional<Admin> findByAdminId(String adminId) {
        String sql = "SELECT * FROM admins WHERE admin_id = ?";
        List<Map<String, Object>> results = jdbcUtil.executeQuery(sql, adminId);
        return results.isEmpty() ? Optional.empty() : Optional.of(mapRowToAdmin(results.get(0)));
    }
    
    /**
     * 根据管理员姓名模糊查询
     */
    @Override
    public List<Admin> findByNameContaining(String namePart) {
        String sql = "SELECT * FROM admins WHERE name LIKE ?";
        return mapResultsToAdmins(jdbcUtil.executeQuery(sql, "%" + namePart + "%"));
    }
    
    /**
     * 判断管理员工号是否存在
     */
    public boolean existsByAdminId(String adminId) {
        String sql = "SELECT COUNT(*) AS count FROM admins WHERE admin_id = ?";
        List<Map<String, Object>> results = jdbcUtil.executeQuery(sql, adminId);
        return !results.isEmpty() && ((Number) results.get(0).get("count")).intValue() > 0;
    }
    
    /**
     * 保存管理员
     */
    @Override
    public Admin save(Admin admin) {
        if (admin.getId() == null) {
            // 插入操作
            String sql = "INSERT INTO admins (name, admin_id, password, email, phone, status, last_login_time, create_time, update_time) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            // 设置创建和更新时间
            LocalDateTime now = LocalDateTime.now();
            if (admin.getCreateTime() == null) {
                admin.setCreateTime(now);
            }
            if (admin.getUpdateTime() == null) {
                admin.setUpdateTime(now);
            }
            
            long id = jdbcUtil.executeInsert(sql,
                    admin.getName(),
                    admin.getAdminId(),
                    admin.getPassword(),
                    admin.getEmail(),
                    admin.getPhone(),
                    admin.getStatus(),
                    admin.getLastLoginTime() != null ? Timestamp.valueOf(admin.getLastLoginTime()) : null,
                    Timestamp.valueOf(admin.getCreateTime()),
                    Timestamp.valueOf(admin.getUpdateTime()));
            
            admin.setId(id);
            return admin;
        } else {
            // 更新操作
            update(admin);
            return admin;
        }
    }
    
    /**
     * 更新管理员
     */
    @Override
    public void update(Admin admin) {
        String sql = "UPDATE admins SET name = ?, password = ?, email = ?, phone = ?, " +
                "status = ?, last_login_time = ?, update_time = ? " +
                "WHERE id = ?";
        
        // 设置更新时间
        admin.setUpdateTime(LocalDateTime.now());
        
        int rows = jdbcUtil.executeUpdate(sql,
                admin.getName(),
                admin.getPassword(),
                admin.getEmail(),
                admin.getPhone(),
                admin.getStatus(),
                admin.getLastLoginTime() != null ? Timestamp.valueOf(admin.getLastLoginTime()) : null,
                Timestamp.valueOf(admin.getUpdateTime()),
                admin.getId());
                
        if (rows <= 0) {
            logger.error("更新管理员信息失败，未更新任何记录: {}", admin.getId());
            throw new BusinessException("更新管理员信息失败");
        }
        
        logger.info("成功更新管理员信息: {}", admin.getId());
    }
    
    /**
     * 删除管理员
     */
    @Override
    public void delete(Long id) {
        String sql = "DELETE FROM admins WHERE id = ?";
        jdbcUtil.executeUpdate(sql, id);
    }
    
    /**
     * 查询总数
     */
    @Override
    public long count() {
        String sql = "SELECT COUNT(*) AS count FROM admins";
        List<Map<String, Object>> results = jdbcUtil.executeQuery(sql);
        if (!results.isEmpty()) {
            return ((Number) results.get(0).get("count")).longValue();
        }
        return 0;
    }
    
    /**
     * 将查询结果映射为管理员对象列表
     */
    private List<Admin> mapResultsToAdmins(List<Map<String, Object>> results) {
        List<Admin> admins = new ArrayList<>();
        for (Map<String, Object> row : results) {
            admins.add(mapRowToAdmin(row));
        }
        return admins;
    }
    
    /**
     * 将单行结果映射为管理员对象
     */
    private Admin mapRowToAdmin(Map<String, Object> row) {
        Admin admin = new Admin();
        
        admin.setId(((Number) row.get("id")).longValue());
        admin.setAdminId((String) row.get("admin_id"));
        admin.setName((String) row.get("name"));
        admin.setPassword((String) row.get("password"));
        admin.setEmail((String) row.get("email"));
        admin.setPhone((String) row.get("phone"));
        
        if (row.get("status") != null) {
            admin.setStatus(((Number) row.get("status")).intValue());
        }
        
        admin.setLastLoginTime(convertToLocalDateTime(row.get("last_login_time")));
        admin.setCreateTime(convertToLocalDateTime(row.get("create_time")));
        admin.setUpdateTime(convertToLocalDateTime(row.get("update_time")));
        
        return admin;
    }
    
    /**
     * 将数据库时间对象转换为LocalDateTime
     */
    private LocalDateTime convertToLocalDateTime(Object timeObj) {
        if (timeObj == null) {
            return null;
        }
        
        if (timeObj instanceof Timestamp) {
            return ((Timestamp) timeObj).toLocalDateTime();
        } else if (timeObj instanceof java.sql.Date) {
            return ((java.sql.Date) timeObj).toLocalDate().atStartOfDay();
        } else if (timeObj instanceof java.util.Date) {
            return ((java.util.Date) timeObj).toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDateTime();
        }
        
        return null;
    }
} 